package cn.xuexiluxian.open.system.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.xuexiluxian.open.common.constant.SystemConfigConstants;
import cn.xuexiluxian.open.common.utils.SecurityUtil;
import cn.xuexiluxian.open.system.mapper.SystemUserMapper;
import cn.xuexiluxian.open.system.model.dto.SystemUserDTO;
import cn.xuexiluxian.open.system.model.entity.SystemConfig;
import cn.xuexiluxian.open.system.model.entity.SystemUser;
import cn.xuexiluxian.open.system.model.entity.SystemUserPost;
import cn.xuexiluxian.open.system.model.entity.SystemUserRole;
import cn.xuexiluxian.open.system.model.req.SystemUserREQ;
import cn.xuexiluxian.open.system.service.ISystemConfigService;
import cn.xuexiluxian.open.system.service.ISystemUserPostService;
import cn.xuexiluxian.open.system.service.ISystemUserRoleService;
import cn.xuexiluxian.open.system.service.ISystemUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class SystemUserService extends ServiceImpl<SystemUserMapper, SystemUser> implements ISystemUserService {
    @Autowired
    private SystemUserMapper systemUserMapper;
    @Autowired
    private ISystemConfigService systemConfigService;
    @Autowired
    private ISystemUserRoleService systemUserRoleService;
    @Autowired
    private ISystemUserPostService systemUserPostService;

    @Override
    public SystemUser selectOneByUserName(String username) {
        return systemUserMapper.selectOneByUserName(username);
    }

    @Override
    public SystemUser selectOneByMobile(String phone) {
        return systemUserMapper.selectOneByMobile(phone);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(String id) {
        int row = systemUserMapper.deleteById(id);
        /**
         * 处理角色
         */
        QueryWrapper<SystemUserRole> userRoleQueryWrapper = new QueryWrapper<SystemUserRole>();
        userRoleQueryWrapper.eq("user_id", id);
        systemUserRoleService.remove(userRoleQueryWrapper);
        /**
         * 处理岗位
         */
        QueryWrapper<SystemUserPost> userPostQueryWrapper = new QueryWrapper<SystemUserPost>();
        userPostQueryWrapper.eq("user_id", id);
        systemUserPostService.remove(userPostQueryWrapper);
        if(row > 0){
            return true;
        }
        return false;
    }

    /**
     * 用户详情
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> detail(String id) {
        Map<String, Object> result = new HashMap<>();
        SystemUser systemUser = systemUserMapper.selectById(id);
        // 处理角色
        List<String> roleIds = systemUserRoleService.selectCheckedByUserId(id);
        // 处理岗位
        List<String> postIds = systemUserPostService.selectCheckedByUserId(id);

        result.put("user", systemUser);
        result.put("roleIds", roleIds);
        result.put("postIds", postIds);
        return result;
    }

    /**
     * 分页用户列表
     * @param page
     * @param params
     * @return
     */
    @Override
    public Page<SystemUser> pageList(Page page, SystemUserREQ params) {
        return systemUserMapper.page(page, params);
    }

    /**
     * 添加用户
     * @param systemUserDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBean(SystemUserDTO systemUserDTO) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String userId = SecurityUtil.getUserId();
        String id = IdUtil.getSnowflakeNextIdStr();

        SystemUser systemUser = new SystemUser();
        BeanUtils.copyProperties(systemUserDTO, systemUser);

        String password = passwordEncoder.encode(systemUserDTO.getPassword());

        systemUser.setId(id);
        systemUser.setPassword(password);
        systemUser.setUserType(0);
        systemUser.setSystemed(0);
        systemUser.setCreateBy(userId);
        systemUser.setCreateTime(new Date());

        int row = systemUserMapper.insert(systemUser);

        /**
         * 处理角色
         */
        List<String> roleIds = systemUserDTO.getRoleIds();
        if(roleIds != null && roleIds.size() > 0){
            List<SystemUserRole> systemUserRoles = new ArrayList<SystemUserRole>();
            for (int i = 0; i < roleIds.size(); i++) {
                SystemUserRole systemUserRole = new SystemUserRole();
                systemUserRole.setUserId(id);
                systemUserRole.setRoleId(roleIds.get(i));
                systemUserRoles.add(systemUserRole);
            }
            systemUserRoleService.saveBatch(systemUserRoles);
        }
        /**
         * 处理岗位
         */
        List<String> postIds = systemUserDTO.getPostIds();
        if(postIds != null && postIds.size() > 0){
            List<SystemUserPost> systemUserPosts = new ArrayList<SystemUserPost>();
            for (int i = 0; i < postIds.size(); i++) {
                SystemUserPost systemUserPost = new SystemUserPost();
                systemUserPost.setUserId(id);
                systemUserPost.setPostId(postIds.get(i));
                systemUserPosts.add(systemUserPost);
            }
            systemUserPostService.saveBatch(systemUserPosts);
        }
        if(row > 0){
            return true;
        }
        return false;
    }

    /**
     * 修改用户
     * @param systemUserDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBean(SystemUserDTO systemUserDTO) {
        String userId = SecurityUtil.getUserId();
        String id = systemUserDTO.getId();

        SystemUser systemUser = new SystemUser();
        BeanUtils.copyProperties(systemUserDTO, systemUser);

        if(StrUtil.isNotBlank(systemUserDTO.getPassword())){
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String password = passwordEncoder.encode(systemUserDTO.getPassword());
            systemUser.setPassword(password);
        }
        systemUser.setSystemed(0);
        systemUser.setUpdateBy(userId);
        systemUser.setUpdateTime(new Date());

        int row = systemUserMapper.updateById(systemUser);

        /**
         * 处理角色
         */
        QueryWrapper<SystemUserRole> userRoleQueryWrapper = new QueryWrapper<SystemUserRole>();
        userRoleQueryWrapper.eq("user_id", id);
        systemUserRoleService.remove(userRoleQueryWrapper);
        List<String> roleIds = systemUserDTO.getRoleIds();
        if(roleIds != null && roleIds.size() > 0){
            List<SystemUserRole> systemUserRoles = new ArrayList<SystemUserRole>();
            for (int i = 0; i < roleIds.size(); i++) {
                SystemUserRole systemUserRole = new SystemUserRole();
                systemUserRole.setUserId(id);
                systemUserRole.setRoleId(roleIds.get(i));
                systemUserRoles.add(systemUserRole);
            }
            systemUserRoleService.saveBatch(systemUserRoles);
        }
        /**
         * 处理岗位
         */
        QueryWrapper<SystemUserPost> userPostQueryWrapper = new QueryWrapper<SystemUserPost>();
        userPostQueryWrapper.eq("user_id", id);
        systemUserPostService.remove(userPostQueryWrapper);
        List<String> postIds = systemUserDTO.getPostIds();
        if(postIds != null && postIds.size() > 0){
            List<SystemUserPost> systemUserPosts = new ArrayList<SystemUserPost>();
            for (int i = 0; i < postIds.size(); i++) {
                SystemUserPost systemUserPost = new SystemUserPost();
                systemUserPost.setUserId(id);
                systemUserPost.setPostId(postIds.get(i));
                systemUserPosts.add(systemUserPost);
            }
            systemUserPostService.saveBatch(systemUserPosts);
        }
        if(row > 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean reset(String id) {
        String userId = SecurityUtil.getUserId();

        SystemConfig systemConfig = systemConfigService.selectOneByKey(SystemConfigConstants.SYSTEM_DEFAULT_PWD);

        SystemUser systemUser = new SystemUser();
        systemUser.setId(id);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode(systemConfig.getV());
        systemUser.setPassword(password);
        systemUser.setUpdateBy(userId);
        systemUser.setUpdateTime(new Date());

        int row = systemUserMapper.updateById(systemUser);

        if(row > 0){
            return true;
        }
        return false;
    }

    /**
     * 授权角色
     * @param list
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean grant(List<SystemUserRole> list) {
        SystemUserRole temp = list.get(0);

        QueryWrapper<SystemUserRole> userRoleQueryWrapper = new QueryWrapper<SystemUserRole>();
        userRoleQueryWrapper.eq("user_id", temp.getUserId());
        systemUserRoleService.remove(userRoleQueryWrapper);

        boolean b = systemUserRoleService.saveBatch(list);
        return b;
    }
}
